public class SSYApprovalController
{
    public String RecordId
     {
           get
           {
               return String.valueOf(System.currentPageReference().getParameters().get('id')).substring(0,15);  
           }
           set;
     }
     public User u
     {
         get
         {
             return [select id,UserRegion__c,UserSubRegion__c,Title__c,Title_Functional__c from User where id=:UserInfo.getUserId()];
         }
     }
     public Boolean CheckAll{get;set;}
     public CommonMethod getCommonMethod;
     public Activity_Information__c ActivityInfo{get;set;}
     public map<string,integer> totalOutletList;
     public map<string,string> StatusList;
     public map<string,string> approvelIdList;
     public List<ApproveDynamicColumnEntryForETAndFG> ETEntryList{get;set;}
    public List<String> ResourceETColumnList{get;set;}
    public List<String> ResourceCostTypeColumnList{get;set;}
    public CommonAttribute getAttribute{get;set;}
    
     public SSYApprovalController()
     {
        ActivityInfo=[select name,Serial_Number__c,Activity_Start_Date__c,Activity_End_Date__c,Activity_Notice__c 
                             from Activity_Information__c where id=:RecordId];
                             
         getCommonMethod=new CommonMethod();
         getAttribute=new CommonAttribute();
         LoadOutletTotalAndStatus();
         LoadApprovalList();
     }
     
     public void LoadOutletTotalAndStatus()
     {
          totalOutletList=new map<string,integer>();
          StatusList=new map<string,string>();
          approvelIdList=new map<string,string>();
         for(Participator_Detail_Area__c area: [select Submit_ASM__c,Outlet_Amount__c,Approve_Type__c,ApprovalId__c,
                                                                 Approve_Description__c from  Participator_Detail_Area__c 
                                                                 where Activity_Information__c=:RecordId
                                                                 and IsActive__c=true])
         {
             if(area!=NULL)
             {
                 if(totalOutletList.containsKey(area.Submit_ASM__c))
                 {
                     Integer num=totalOutletList.get(area.Submit_ASM__c);
                     num+=Integer.valueOf(area.Outlet_Amount__c);
                     totalOutletList.put(area.Submit_ASM__c,num);
                 }
                 else
                 {
                     Decimal num=area.Outlet_Amount__c;
                     totalOutletList.put(area.Submit_ASM__c,num.intValue());
                 }
                 approvelIdList.put(area.Submit_ASM__c,area.ApprovalId__c);
                 if(area.Approve_Description__c!=NULL && area.Approve_Description__c!='')
                    StatusList.put(area.Submit_ASM__c,area.Approve_Type__c+'('+area.Approve_Description__c+')');
                  else
                     StatusList.put(area.Submit_ASM__c,area.Approve_Type__c);
             }
         }
     }
     public void LoadApprovalList()
     {
         String Refilter='';
         String Cofilter='';
         if(u.Title__c=='Regional Sales Manager'){
            Refilter+=' and Participator_Detail_Area__r.Submit_ASM__r.Manager.id=\''+u.id+'\' and Participator_Detail_Area__r.Approve_Type__c=\'ASM已提交\'';
            Cofilter+=' and SubmitASM__r.Submit_ASM__r.Manager.id=\''+u.id+'\' and SubmitASM__r.Approve_Type__c=\'ASM已提交\'';
          }else if(u.Title_Functional__c=='RTM'){
            Refilter+=' and Participator_Detail_Area__r.SubRegion__c=\''+u.UserSubRegion__c+'\'';
            Cofilter+=' and SubmitASM__r.SubRegion__c=\''+u.UserSubRegion__c+'\'';
          }else if(u.Title_Functional__c=='SRTM'){
            Refilter+=' and Participator_Detail_Area__r.Region__c=\''+u.UserRegion__c+'\'';
            Cofilter+=' and SubmitASM__r.Region__c=\''+u.UserRegion__c+'\'';
            }
         string sqlResourceStr='select sum(Resource_Quantity_Number__c) SumTotal,Participator_Detail_Area__r.Submit_ASM__c,'+
                                             ' Participator_Detail_Area__r.Submit_ASM__r.Name,'+
                                              ' Participator_Detail_Area__r.Submit_ASM__r.Email,'+
                                             ' Resource_Allocation__r.Product_Name__r.Name ResourceName '+
                                             ' from Resource_Allocation_Detail__c '+
                                             ' where ActivityId__c=\''+RecordId+'\' and Participator_Detail_Area__r.Submit_ASM__c!=NULL and Participator_Detail_Area__r.IsActive__c=true '
                                             +Refilter;
                                             
      string sqlCompetitionStr='select sum(Money__c) SumTotal,SubmitASM__r.Submit_ASM__c,'+
                                               ' SubmitASM__r.Submit_ASM__r.Name,'+
                                          //      ' SubmitASM__r.Submit_ASM__r.Email,'+
                                               ' Activity_Competition_Brand_Information__r.Competition_Cost_Type__c ResourceName'+
                                               ' from Activity_Competition_Brand_Detail__c'+ 
                                               ' where ActivityId__c=\''+RecordId+'\' and SubmitASM__r.Submit_ASM__c!=NULL and SubmitASM__r.IsActive__c=true'
                                               +Cofilter;
                                               
      if(getAttribute.RegionSelectedValue!=NULL && getAttribute.RegionSelectedValue!='0')
      {
          sqlResourceStr+=' and Participator_Detail_Area__r.Submit_ASM__r.UserRegion__c =\''+getAttribute.RegionSelectedValue+'\'';
          sqlCompetitionStr+=' and SubmitASM__r.Submit_ASM__r.UserRegion__c =\''+getAttribute.RegionSelectedValue+'\'';
      }
      if(getAttribute.SubRegionSelectedValue != NULL && getAttribute.SubRegionSelectedValue !='0')  
      {
          sqlResourceStr+=' and Participator_Detail_Area__r.Submit_ASM__r.UserSubRegion__c =\''+getAttribute.SubRegionSelectedValue +'\'';
          sqlCompetitionStr+=' and SubmitASM__r.Submit_ASM__r.UserSubRegion__c =\''+getAttribute.SubRegionSelectedValue +'\'';
      }   
      if(getAttribute.AreaSelectedValue!=NULL && getAttribute.AreaSelectedValue!='0')
      {
          sqlResourceStr+=' and Participator_Detail_Area__r.Area__c like \'%'+getAttribute.AreaSelectedValue+'%\'';
          sqlCompetitionStr+=' and SubmitASM__r.Area__c like \'%'+getAttribute.AreaSelectedValue+'%\'';
      }        
      
       sqlResourceStr+= ' GROUP BY Participator_Detail_Area__r.Submit_ASM__c,Participator_Detail_Area__r.Submit_ASM__r.Name,'+
                                              ' Participator_Detail_Area__r.Submit_ASM__r.Email,'+
                                             ' Resource_Allocation__r.Product_Name__r.Name'+
                                             ' order by Resource_Allocation__r.Product_Name__r.Name asc';
       sqlCompetitionStr+=' group by SubmitASM__r.Submit_ASM__c,SubmitASM__r.Submit_ASM__r.Name,'+
                                      //   ' SubmitASM__r.Submit_ASM__r.Email,'+
                                        ' Activity_Competition_Brand_Information__r.Competition_Cost_Type__c'+
                                        ' order by Activity_Competition_Brand_Information__r.Competition_Cost_Type__c asc';
      //  throw new CustomException(sqlResourceStr);               
                
         Map<String,ApproveDynamicColumnEntryForETAndFG> mapList=new map<String,ApproveDynamicColumnEntryForETAndFG>();//资源列表
         ETEntryList=new List<ApproveDynamicColumnEntryForETAndFG>();
         List<AggregateResult> groupResourceList=Database.query(sqlResourceStr);
                                                                                    
         ResourceETColumnList=getCommonMethod.GetDynamicETColumnList(groupResourceList);//获取列
    
         List<AggregateResult> competitionList=DataBase.query(sqlCompetitionStr);                                                    
         ResourceCostTypeColumnList=getCommonMethod.GetDynamicETColumnList(competitionList);//获取竞品费用类型列
         
          for(AggregateResult rs:groupResourceList)      
         {
              
             String  resourceName=(String)rs.get('ResourceName');
             Decimal reNum=(Decimal)rs.get('SumTotal');
             String num=String.valueOf(reNum);
            
             if(!mapList.containsKey((String)rs.get('Submit_ASM__c')))
             {   
                 List<String> resourceNumList=new String[ResourceETColumnList.size()];
                 List<String> CostTypeNumList=new String[ResourceCostTypeColumnList.size()];
                 for(integer i=0;i<CostTypeNumList.size();i++){
                    CostTypeNumList[i]=' ';
                  }
                  for(integer j=0;j<resourceNumList.size();j++){
                    resourceNumList[j]=' ';
                  }
                 
                 ApproveDynamicColumnEntryForETAndFG entry=new ApproveDynamicColumnEntryForETAndFG();
                 entry.CostTypeNumList=CostTypeNumList;
                 entry.IsCheck=false;
                 if(u.Title__c=='Regional Sales Manager')
                 {
                     if(StatusList.get((String)rs.get('Submit_ASM__c'))=='ASM已提交')
                         entry.ApproveStatus='待审批';
                 }
                 else if(u.Title_Functional__c=='RTM')
                 {
                     if(StatusList.get((String)rs.get('Submit_ASM__c'))=='RSM已审批(同意)')
                         entry.ApproveStatus='待审批';
                 }   
                 else if(u.Title_Functional__c=='SRTM')     
                 {
                     if(u.id==ActivityManagementApproval__c.getValues('SOC').UserRecordId__c || 
                         u.id==ActivityManagementApproval__c.getValues('EOC').UserRecordId__c ||
                         u.id==ActivityManagementApproval__c.getValues('NOC').UserRecordId__c)
                      {
                             if(StatusList.get((String)rs.get('Submit_ASM__c'))=='RTM已审批(同意)' || StatusList.get((String)rs.get('Submit_ASM__c'))=='RSM已审批(同意)')
                                 entry.ApproveStatus='待审批';
                      }
                      else
                      {
                           if(StatusList.get((String)rs.get('Submit_ASM__c'))=='RTM已审批(同意)' )
                                 entry.ApproveStatus='待审批';
                      }
                 }
                 else
                 {
                      entry.ApproveStatus=StatusList.get((String)rs.get('Submit_ASM__c'));
                 }
                 entry.ApprovalId=(string)approvelIdList.get((String)rs.get('Submit_ASM__c'));
                 entry.Name=(String)rs.get('name');
                 entry.email=(String)rs.get('Email');
                 entry.OutletTotalNumber=(Integer)totalOutletList.get((String)rs.get('Submit_ASM__c'));
              
                  integer i=0;
                  for(String name:ResourceETColumnList){
                    if(name==resourceName)
                       resourceNumList[i]=num;
                    i++;
                  }
                entry.resourceNumList=resourceNumList;
                mapList.put((String)rs.get('Submit_ASM__c'),entry);
             }
             else
             {
                  ApproveDynamicColumnEntryForETAndFG entry=mapList.get((String)rs.get('Submit_ASM__c'));
                  integer i=0;
                    for(String name:ResourceETColumnList){
                        if(name==resourceName)
                             entry.resourceNumList[i]=num;
                       i++;
                        }
                         mapList.put((String)rs.get('Submit_ASM__c'),entry);
             }
         }   
       //  System.assert(false,competitionList);
         //添加竞品数据 
         for(AggregateResult rs:competitionList)   
         { 
             String comType=(String)rs.get('ResourceName');
             Decimal reNum=(Decimal)rs.get('SumTotal');
             String num=String.valueOf(reNum);
             //判断当某种竞品类型下的竞品明细全为null时设置总金额为0
               if(reNum==null)
                 num='0.0';
                  if(mapList.containsKey((String)rs.get('Submit_ASM__c')))
                  {  
                     ApproveDynamicColumnEntryForETAndFG entry=mapList.get((String)rs.get('Submit_ASM__c'));
                     integer i=0;
                     for(String name:ResourceCostTypeColumnList){
                        if(name==comType)
                          entry.CostTypeNumList[i]=num;
                         i++;
                      }     
                      mapList.put((String)rs.get('Submit_ASM__c'),entry);
                 }else{     
              
                     List<String> resourceNumList=new String[ResourceETColumnList.size()];
                    List<String> CostTypeNumList=new String[ResourceCostTypeColumnList.size()];
                   for(integer i=0;i<CostTypeNumList.size();i++){
                    CostTypeNumList[i]=' ';
                    }
                  for(integer j=0;j<resourceNumList.size();j++){
                    resourceNumList[j]=' ';
                   }
                 
                 ApproveDynamicColumnEntryForETAndFG entry=new ApproveDynamicColumnEntryForETAndFG();
                 entry.CostTypeNumList=CostTypeNumList;
                 entry.IsCheck=false;
                 if(u.Title__c=='Regional Sales Manager')
                 {
                     if(StatusList.get((String)rs.get('Submit_ASM__c'))=='ASM已提交')
                         entry.ApproveStatus='待审批';
                 }
                 else if(u.Title_Functional__c=='RTM')
                 {
                     if(StatusList.get((String)rs.get('Submit_ASM__c'))=='RSM已审批(同意)')
                         entry.ApproveStatus='待审批';
                 }   
                 else if(u.Title_Functional__c=='SRTM')     
                 {
                     if(u.id==ActivityManagementApproval__c.getValues('SOC').UserRecordId__c || 
                         u.id==ActivityManagementApproval__c.getValues('EOC').UserRecordId__c ||
                         u.id==ActivityManagementApproval__c.getValues('NOC').UserRecordId__c)
                      {
                             if(StatusList.get((String)rs.get('Submit_ASM__c'))=='RTM已审批(同意)' || StatusList.get((String)rs.get('Submit_ASM__c'))=='RSM已审批(同意)')
                                 entry.ApproveStatus='待审批';
                      }
                      else
                      {
                           if(StatusList.get((String)rs.get('Submit_ASM__c'))=='RTM已审批(同意)' )
                                 entry.ApproveStatus='待审批';
                      }
                 }
                 else
                 {
                      entry.ApproveStatus=StatusList.get((String)rs.get('Submit_ASM__c'));
                 }
                 entry.ApprovalId=(string)approvelIdList.get((String)rs.get('Submit_ASM__c'));
                 entry.Name=(String)rs.get('name');
                 entry.OutletTotalNumber=(Integer)totalOutletList.get((String)rs.get('Submit_ASM__c'));
              
                  integer i=0;
                   for(String name:ResourceCostTypeColumnList){
                        if(name==comType)
                          entry.CostTypeNumList[i]=num;
                     i++;
                  }
                    
                entry.resourceNumList=resourceNumList;
                mapList.put((String)rs.get('Submit_ASM__c'),entry);   

              }
          
         }
         //找出所有的直接汇报给RSM的ASM
          if(u.Title__c=='Regional Sales Manager')
          {
            for(User u:getCommonMethod.getASMList(u.UserSubRegion__c)) 
            {
                     if(!mapList.containsKey(u.id))
                     {   
                         List<String> resourceNumList=new String[ResourceETColumnList.size()];
                         List<String> CostTypeNumList=new String[ResourceCostTypeColumnList.size()];
                         for(integer i=0;i<CostTypeNumList.size();i++){
                            CostTypeNumList[i]=' ';
                          }
                          for(integer j=0;j<resourceNumList.size();j++){
                            resourceNumList[j]=' ';
                          }
                         
                         ApproveDynamicColumnEntryForETAndFG entry=new ApproveDynamicColumnEntryForETAndFG();
                         entry.CostTypeNumList=CostTypeNumList;
                         entry.resourceNumList=resourceNumList;
                         
                         entry.IsCheck=false;
                         entry.ApproveStatus='未提交';
                         //entry.ApprovalId=(string)approvelIdList.get((String)rs.get('Submit_ASM__c'));
                         entry.Name=u.Name;
                         entry.email=u.Email;
                        
                        mapList.put(u.Id,entry);
                     }
                }
          }
          //排序，未提交的放到最下面
          List<ApproveDynamicColumnEntryForETAndFG> UncommittedEntryList=new List<ApproveDynamicColumnEntryForETAndFG>();
          List<ApproveDynamicColumnEntryForETAndFG> CommittedEntryList=new List<ApproveDynamicColumnEntryForETAndFG>();
          for(ApproveDynamicColumnEntryForETAndFG entry:mapList.values())
          {
              if(entry.ApproveStatus=='未提交')
                  UncommittedEntryList.add(entry);
              else
                  CommittedEntryList.add(entry);
          }
          ETEntryList.addAll(CommittedEntryList);
          ETEntryList.addAll(UncommittedEntryList);
     }
    
     public pageReference QueryApprovalList()
     {
         LoadApprovalList();
         return null;
     }
     public PageReference ApprovedProce()
     {
         List<String> emailList=new List<String>();  //ASM邮件地址
         for(ApproveDynamicColumnEntryForETAndFG app:ETEntryList)
         {
             if(app.IsCheck && app.ApproveStatus=='待审批')//
             {
                emailList.add(app.email);
                 Participator_Detail_Area__c par=[select ApprovalId__c from Participator_Detail_Area__c where ApprovalId__c=:app.ApprovalId];
                 app.ApproveStatus='已审批';
                Approval.ProcessWorkitemRequest req2 = new Approval.ProcessWorkitemRequest();
                req2.setComments('同意');
                req2.setAction('Approve');
                req2.setWorkitemId(app.ApprovalId);
                
                Approval.ProcessResult result2 =  Approval.process(req2);

               if(result2.getNewWorkitemIds()!=NULL && result2.getNewWorkitemIds().size()>0)
               {            
                   par.ApprovalId__c=(String)result2.getNewWorkitemIds().get(0);
                   update par;
                 //  发送邮件给ASM，进行最后的时间确认
                 /*
                   if(u.Title_Functional__c=='SRTM' || u.Title_Functional__c=='RTM'){
                     System.assert(false,emailList);
                     String BodyString='请登陆凤凰系统，确认【'+ActivityInfo.Name+'】活动竞品时间的最后确认';
                     String subject='活动竞品时间最后确认，活动名称:'+ActivityInfo.Name;
                     EmailHander.SendMail(BodyString,emailList,subject,'',null);
                     
                   }*/
              }
            }
        }
        return null;
     }
     public PageReference RejectCompetitionProcess()
     {
          for(ApproveDynamicColumnEntryForETAndFG app:ETEntryList)
         {
             if(app.IsCheck && app.ApproveStatus=='待审批')
             {
                 Participator_Detail_Area__c par=[select ApprovalId__c from Participator_Detail_Area__c where ApprovalId__c=:app.ApprovalId];
                 app.ApproveStatus='已审批';
                Approval.ProcessWorkitemRequest req2 = new Approval.ProcessWorkitemRequest();
                req2.setComments('竞品费用填写不合理');
                req2.setAction('Reject');
                req2.setWorkitemId(app.ApprovalId);
                Approval.ProcessResult result2 =  Approval.process(req2);
                 if(result2.getNewWorkitemIds()!=NULL && result2.getNewWorkitemIds().size()>0)
                {
                   par.ApprovalId__c=(String)result2.getNewWorkitemIds().get(0);
                   update par;
               }
            }
        }
         return null;
     }
     
     public PageReference RejectResourceProcess()
     {
          for(ApproveDynamicColumnEntryForETAndFG app:ETEntryList)
         {
             if(app.IsCheck && app.ApproveStatus=='待审批')
             {
                 Participator_Detail_Area__c par=[select ApprovalId__c from Participator_Detail_Area__c where ApprovalId__c=:app.ApprovalId];
                 app.ApproveStatus='已审批';
                Approval.ProcessWorkitemRequest req2 = new Approval.ProcessWorkitemRequest();
                req2.setComments('教育工具分配不合理');
                req2.setAction('Reject');
                req2.setWorkitemId(app.ApprovalId);
                Approval.ProcessResult result2 =  Approval.process(req2);
                 if(result2.getNewWorkitemIds()!=NULL && result2.getNewWorkitemIds().size()>0)
                {
                   par.ApprovalId__c=(String)result2.getNewWorkitemIds().get(0);
                   update par;
               }
            }
        }
         return null;
     }
}